<template>
    <div class="create-paper-container">
        <!-- 标题栏 -->
        <div class="title-bar">
            <span class="title" :class="{ active: currentTab === 'basicInfo' }"
                @click="currentTab = 'basicInfo'">基本信息</span>
            <span class="title" :class="{ active: currentTab === 'questionType' }"
                @click="currentTab = 'questionType'">题型配置</span>
            <span class="title" :class="{ active: currentTab === 'permission' }"
                @click="currentTab = 'permission'">权限配置</span>
            <span class="title" :class="{ active: currentTab === 'other' }" @click="currentTab = 'other'">其他配置</span>
        </div>
        <!-- 滚动容器 -->
        <div class="scroll-container">
            <!-- 基本信息表单 -->
            <div v-if="currentTab === 'basicInfo'" class="form-container">
                <el-form :model="paperInfo" label-width="150px" class="basic-info-form">
                    <el-form-item label="试卷名称">
                        <el-input v-model="paperInfo.paperName" placeholder="请输入试卷名称"></el-input>
                    </el-form-item>
                    <el-form-item label="试卷说明">
                        <el-input v-model="paperInfo.paperDescription" placeholder="请输入试卷说明" type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item label="考试时长">
                        <div class="input-with-buttons">
                            <el-button @click="decrease('examDuration')">-</el-button>
                            <el-input v-model.number="paperInfo.examDuration" style="width: 80px;"></el-input>
                            <el-button @click="increase('examDuration')">+</el-button>
                            <span>分钟</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="试卷总分">
                        <div class="input-with-buttons">
                            <el-button @click="decrease('totalScore')">-</el-button>
                            <el-input v-model.number="paperInfo.totalScore" style="width: 80px;"></el-input>
                            <el-button @click="increase('totalScore')">+</el-button>
                            <span>分</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="及格分数">
                        <div class="input-with-buttons">
                            <el-button @click="decrease('passScore')">-</el-button>
                            <el-input v-model.number="paperInfo.passScore" style="width: 80px;"></el-input>
                            <el-button @click="increase('passScore')">+</el-button>
                            <span>分</span>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 题型配置表单 -->
            <div v-if="currentTab === 'questionType'" class="form-container question-type-scrollable">
                <el-form :model="questionTypeConfig" label-width="150px" class="basic-info-form">
                    <el-form-item label="题库选择">
                        <el-select v-model="paperInfo.questionBank" placeholder="请选择题库" style="width: 100%">
                            <el-option
                                v-for="bank in questionBanks"
                                :key="bank.id"
                                :label="bank.name"
                                :value="bank.id"
                            >
                                <span>{{ bank.name }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">
                                    ({{ bank.questionCount }}题)
                                </span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="题型选择">
                        <el-checkbox-group v-model="questionTypeConfig.selectedTypes">
                            <el-checkbox 
                                v-for="type in ['单选题', '多选题', '判断题', '填空题', '问答题', '组合题']"
                                :key="type"
                                :label="type"
                                :disabled="getQuestionTypeCount(type) === 0"
                            >
                                {{ type }}
                                <span style="color: #8492a6; margin-left: 8px">
                                    ({{ getQuestionTypeCount(type) }}题)
                                </span>
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <template v-for="type in questionTypeConfig.selectedTypes" :key="type">
                        <el-form-item :label="type + '个数'">
                            <el-input-number 
                                v-model="questionTypeConfig[type].count" 
                                :min="0" 
                                :max="getQuestionTypeCount(type)"
                                placeholder="请输入个数"
                            ></el-input-number>
                            <span style="margin-left: 8px; color: #8492a6">
                                最多可选 {{ getQuestionTypeCount(type) }} 题
                            </span>
                        </el-form-item>
                        <el-form-item :label="type + '分值'">
                            <el-input-number 
                                v-model="questionTypeConfig[type].score" 
                                :min="0"
                                placeholder="请输入分值"
                            ></el-input-number>
                            <span style="margin-left: 8px">分</span>
                        </el-form-item>
                        <el-form-item :label="type + '规则'">
                            <el-input 
                                v-model="questionTypeConfig[type].rule" 
                                placeholder="请输入规则"
                                type="textarea"
                            ></el-input>
                        </el-form-item>
                    </template>
                </el-form>
            </div>
            <!-- 权限配置表单 -->
            <div v-if="currentTab === 'permission'" class="form-container">
                <el-form :model="permissionConfig" label-width="150px" class="basic-info-form">
                    <el-form-item label="答题限制选项">
                        <el-select v-model="permissionConfig.answerRestrictions" placeholder="请选择答题限制">
                            <el-option label="每人一次" value="once"></el-option>
                            <el-option label="每人两次" value="twice"></el-option>
                            <el-option label="每人三次" value="thrice"></el-option>
                            <el-option label="无限制" value="unlimited"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="试卷密码">
                        <el-input v-model="permissionConfig.paperPassword" placeholder="请输入试卷密码"></el-input>
                    </el-form-item>
                    <el-form-item label="发布考试">
                        <el-switch v-model="permissionConfig.publishExam"></el-switch>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 其他配置表单 -->
            <div v-if="currentTab === 'other'" class="form-container">
                <el-form :model="otherConfig" label-width="150px" class="basic-info-form">
                    <el-form-item label="答题成绩发布方式">
                        <el-radio-group v-model="otherConfig.scoreReleaseMethod">
                            <el-radio label="automatic">考完自动发布</el-radio>
                            <el-radio label="manual">手动发布</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="题库练习开关">
                        <el-switch v-model="otherConfig.questionBankPractice"></el-switch>
                    </el-form-item>
                    <el-form-item label="允许切屏次数">
                        <el-select v-model="otherConfig.screenSwitchLimit" placeholder="请选择允许切屏次数">
                            <el-option label="一次" value="once"></el-option>
                            <el-option label="两次" value="twice"></el-option>
                            <el-option label="三次" value="thrice"></el-option>
                            <el-option label="无限制" value="unlimited"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="考试结束语">
                        <el-input v-model="otherConfig.examEndMessage" placeholder="请输入考试结束语"
                            type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item label="答题明细显示">
                        <el-switch v-model="otherConfig.showAnswerDetails"></el-switch>
                    </el-form-item>
                    <el-form-item label="成绩排行榜显示">
                        <el-switch v-model="otherConfig.showScoreRanking"></el-switch>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
    <div class="bottom-submit">
        <el-form-item>
            <el-button type="primary" size="large" @click="submitAllConfigurations">提交所有配置</el-button>
        </el-form-item>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 题库列表
const questionBanks = ref([]);

// 获取题库列表
const fetchQuestionBanks = () => {
  const storedBanks = localStorage.getItem('questionBanks');
  if (storedBanks) {
    questionBanks.value = JSON.parse(storedBanks).map((bank) => ({
      id: bank.id,
      name: bank.name,
      questionCount: bank.questionCount || (bank.questions ? bank.questions.length : 0)
    }));
  }
};

onMounted(() => {
  fetchQuestionBanks();
});

// 试卷信息
const paperInfo = ref({
    paperName: '',
    paperDescription: '',
    examDuration: 60,
    totalScore: 100,
    passScore: 60,
    questionBank: ''
});

// 当前激活的标签页
const currentTab = ref('basicInfo');

// 题型配置信息
const questionTypeConfig = ref({
    selectedTypes: [],
    单选题: { count: 0, score: 0, rule: '' },
    多选题: { count: 0, score: 0, rule: '' },
    判断题: { count: 0, score: 0, rule: '' },
    填空题: { count: 0, score: 0, rule: '' },
    问答题: { count: 0, score: 0, rule: '' },
    组合题: { count: 0, score: 0, rule: '' }
});

// 权限配置信息
const permissionConfig = ref({
    answerRestrictions: 'once',
    paperPassword: '',
    publishExam: false,
});

// 其他配置信息
const otherConfig = ref({
    scoreReleaseMethod: 'automatic',
    questionBankPractice: false,
    screenSwitchLimit: 'unlimited',
    examEndMessage: '',
    showAnswerDetails: false,
    showScoreRanking: false
});

// 在script部分添加新的响应式变量和函数
const selectedBankQuestions = ref([]);

// 监听题库选择变化
const watchQuestionBank = () => {
  if (paperInfo.value.questionBank) {
    const storedBanks = localStorage.getItem('questionBanks');
    if (storedBanks) {
      const banks = JSON.parse(storedBanks);
      const selectedBank = banks.find(bank => bank.id === paperInfo.value.questionBank);
      if (selectedBank && selectedBank.questions) {
        selectedBankQuestions.value = selectedBank.questions;
        
        // 重置题型配置
        questionTypeConfig.value.selectedTypes = [];
        
        // 更新每种题型的配置
        const typeMap = {
          '单选题': 'choice',
          '多选题': 'multiple',
          '判断题': 'judge',
          '填空题': 'fill',
          '问答题': 'essay',
          '组合题': 'combination'
        };

        // 遍历所有题型，更新配置
        Object.entries(typeMap).forEach(([displayType, internalType]) => {
          const count = selectedBank.questions.filter(q => q.type === internalType).length;
          questionTypeConfig.value[displayType] = {
            count: 0,
            score: 0,
            rule: '',
            available: count > 0
          };
        });
      }
    }
  } else {
    selectedBankQuestions.value = [];
    // 清空所有题型配置
    Object.keys(questionTypeConfig.value).forEach(key => {
      if (key !== 'selectedTypes') {
        questionTypeConfig.value[key] = { count: 0, score: 0, rule: '', available: false };
      }
    });
    questionTypeConfig.value.selectedTypes = [];
  }
};

// 获取题型对应的题目数量
const getQuestionTypeCount = (type) => {
  if (!selectedBankQuestions.value.length) return 0;
  
  const typeMap = {
    '单选题': 'choice',
    '多选题': 'multiple',
    '判断题': 'judge',
    '填空题': 'fill',
    '问答题': 'essay',
    '组合题': 'combination'
  };
  
  return selectedBankQuestions.value.filter(q => q.type === typeMap[type]).length;
};

// 监听题库选择
watch(() => paperInfo.value.questionBank, watchQuestionBank, { immediate: true });

// 增加数值
const increase = (field) => {
    paperInfo.value[field]++;
};

// 减少数值
const decrease = (field) => {
    if (paperInfo.value[field] > 0) {
        paperInfo.value[field]--;
    }
};

// 提交所有配置
const submitAllConfigurations = () => {
    const newPaper = {
        id: Date.now().toString(),
        paperName: paperInfo.value.paperName,
        createTime: new Date().toLocaleString(),
        totalScore: paperInfo.value.totalScore,
        paperInfo: paperInfo.value,
        questionTypeConfig: questionTypeConfig.value,
        permissionConfig: permissionConfig.value,
        otherConfig: otherConfig.value
    };
    
    let paperList = JSON.parse(localStorage.getItem('paperList') || '[]');
    paperList.push(newPaper);
    localStorage.setItem('paperList', JSON.stringify(paperList));
    
    ElMessage.success('试卷创建成功！');
    router.push('/main/paper/list');
};
</script>

<style scoped>
.create-paper-container {
    padding: 30px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    margin: 20px auto;
    max-width: 800px;
    height:400px;
    /* 设置容器高度 */
    position: relative;
}

.title-bar {
    display: flex;
    margin-bottom: 30px;
}

.title {
    cursor: pointer;
    margin-right: 20px;
    padding-bottom: 5px;
    border-bottom: 2px solid transparent;
}

.title.active {
    border-bottom-color: #007bff;
}

.form-container {
    margin-bottom: 20px;
}

.question-type-scrollable {
    max-height: 350px;
    overflow-y: auto;
}

.bottom-submit {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    margin-bottom: 30px;
}

.bottom-submit .el-button {
    padding: 12px 40px;
    font-size: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.bottom-submit .el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>